<template>
  <div class="comment-section mt-4">
    <h3>评论 ({{ totalComments }})</h3>
    <el-form :model="newComment" ref="commentFormRef" @submit.prevent="submitComment" v-if="isAuthenticated">
      <el-form-item prop="content" :rules="[{ required: true, message: '评论内容不能为空', trigger: 'blur' }]">
        <el-input 
          type="textarea" 
          :rows="3" 
          v-model="newComment.content" 
          placeholder="发表你的看法...">
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitComment" :loading="submitting">发表评论</el-button>
      </el-form-item>
    </el-form>
    <p v-else>
      请<router-link to="/login">登录</router-link>后发表评论。
    </p>

    <el-divider v-if="comments.length > 0"></el-divider>

    <div v-if="loadingComments" class="loading-comments">
        <el-skeleton :rows="3" animated />
    </div>
    <div v-else-if="comments.length === 0 && !loadingComments">
      <el-empty description="暂无评论"></el-empty>
    </div>
    <div v-else class="comment-list">
      <el-card v-for="comment in comments" :key="comment.id" class="comment-card">
        <template #header>
          <div class="comment-author">
            <el-avatar :size="30" :src="comment.author.avatar || defaultAvatar" class="mr-2"></el-avatar>
            <strong>{{ comment.author.username }}</strong>
            <span class="comment-time ml-2">{{ new Date(comment.createdAt).toLocaleString() }}</span>
          </div>
        </template>
        <p>{{ comment.content }}</p>
        <div class="comment-actions" v-if="isAuthenticated && currentUser.userId === comment.author.id">
          <!-- Edit comment functionality can be added here -->
          <el-popconfirm title="确定删除这条评论吗?" @confirm="deleteComment(comment.id)">
            <template #reference>
              <el-button type="danger" size="small" link>删除</el-button>
            </template>
          </el-popconfirm>
        </div>
      </el-card>
      <el-pagination
        v-if="totalComments > commentsPerPage"
        background
        layout="prev, pager, next"
        :total="totalComments"
        :page-size="commentsPerPage"
        @current-change="handleCommentPageChange"
        class="mt-4"
      >
      </el-pagination>
    </div>
  </div>
</template>

<script>
import { ref, reactive, onMounted, computed, watch } from 'vue';
import axios from 'axios';
import { ElMessage } from 'element-plus';

export default {
  name: 'CommentSection',
  props: {
    articleId: {
      type: [String, Number],
      required: true
    }
  },
  setup(props) {
    const comments = ref([]);
    const loadingComments = ref(true);
    const submitting = ref(false);
    const commentFormRef = ref(null);
    const totalComments = ref(0);
    const currentCommentPage = ref(1);
    const commentsPerPage = ref(5); // Or make this a prop
    const defaultAvatar = "https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png";

    const newComment = reactive({
      content: ''
    });

    const isAuthenticated = computed(() => !!localStorage.getItem('token'));
    const currentUser = computed(() => JSON.parse(localStorage.getItem('user') || '{}'));

    const fetchComments = async (page = 1) => {
      if (!props.articleId) return;
      loadingComments.value = true;
      try {
        const response = await axios.get(`/api/articles/${props.articleId}/comments?current=${page}&size=${commentsPerPage.value}`);
        comments.value = response.data.records;
        totalComments.value = response.data.total;
        currentCommentPage.value = page;
      } catch (error) {
        ElMessage.error('获取评论失败');
        console.error(error);
      } finally {
        loadingComments.value = false;
      }
    };

    const submitComment = async () => {
      if (!commentFormRef.value) return;
      commentFormRef.value.validate(async (valid) => {
        if (valid) {
          submitting.value = true;
          try {
            const token = localStorage.getItem('token');
            await axios.post(`/api/articles/${props.articleId}/comments`, newComment, {
              headers: { Authorization: `Bearer ${token}` }
            });
            newComment.content = ''; // Clear form
            ElMessage.success('评论发表成功');
            fetchComments(currentCommentPage.value); // Refresh comments
          } catch (error) {
            ElMessage.error(error.response?.data?.message || '发表评论失败');
            console.error(error);
          } finally {
            submitting.value = false;
          }
        }
      });
    };

    const deleteComment = async (commentId) => {
      try {
        const token = localStorage.getItem('token');
        await axios.delete(`/api/comments/${commentId}`, {
          headers: { Authorization: `Bearer ${token}` }
        });
        ElMessage.success('评论删除成功');
        fetchComments(currentCommentPage.value); // Refresh comments
      } catch (error) {
        ElMessage.error(error.response?.data?.message || '删除评论失败');
        console.error(error);
      }
    };

    const handleCommentPageChange = (page) => {
      fetchComments(page);
    };

    watch(() => props.articleId, (newId) => {
      if (newId) {
        fetchComments();
      }
    }, { immediate: true });

    return {
      comments,
      loadingComments,
      submitting,
      newComment,
      commentFormRef,
      isAuthenticated,
      currentUser,
      totalComments,
      commentsPerPage,
      defaultAvatar,
      submitComment,
      deleteComment,
      handleCommentPageChange,
      fetchComments // Expose if needed by parent
    };
  }
};
</script>

<style scoped>
.comment-section {
  margin-top: 30px;
  background-color: #f9fafb;
  padding: 20px;
  border-radius: 8px;
}
.comment-card {
  margin-bottom: 15px;
}
.comment-author {
  display: flex;
  align-items: center;
  font-size: 0.9em;
}
.comment-time {
  color: #909399;
  font-size: 0.9em;
}
.comment-actions {
  text-align: right;
  margin-top: 10px;
}
.mr-2 {
  margin-right: 8px;
}
.ml-2 {
  margin-left: 8px;
}
.mt-4 {
  margin-top: 20px;
}
</style> 